import React, { Component, Suspense } from "react";
import { connect } from "dva";
import GridContent from "@/components/PageHeaderWrapper/GridContent";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import PageLoading from "@/components/PageLoading";
import { Card, Button, Icon, Modal, message, Spin } from "antd";
import KnowMap from "@/pages/KnowledgeGraph/edit/knowMap";
import AddCategoryModal from "@/pages/KnowledgeGraph/edit/addCategoryModal";
import TypeNodeEdit from "@/pages/KnowledgeGraph/editDrawer/typeNode";
import Legend from "@/pages/KnowledgeGraph/edit/legend";
import Intentions from "@/pages/KnowledgeGraph/editDrawer/intentions";
import G6 from "@antv/g6";
import TypeNodeInfo from "@/pages/KnowledgeGraph/editDrawer/typeNodeInfo";
import IntentionsNodeInfo from "@/pages/KnowledgeGraph/editDrawer/intentionsNodeInfo";
import { knowledgeAtlasTree } from "@/services/knowledgegraph";
import UserSession from "@/UserSession";
const { confirm } = Modal;

@connect(({ knowledgeGraphEdit, loading }) => ({
	knowledgeGraphEdit,
	loading: loading.effects["knowledgeGraphEdit/getGraphDetail"],
}))
class GraphEdit extends Component {
	state = {
		data: null,
		visible: false,
		type: "",
		selectNode: null,
		graphObj: null,
		nodeColor: "",
		textColor: "",
		editShow: false,
		graphScaleNum: 100,
		id: "",
		name: "",
		editMind: false,
		selectNodeNew: null,
	};

	componentDidMount() {
		const { id, name } = this.props.location.query;

		this.setState({ id, name, }, () => {
			this.getGraphInfo();
		});
	}

	componentWillUnmount() {
		this.setState({
			graphObj: null,
		});
	}

	getGraphInfo = async () => {
		const { dispatch } = this.props;
		const { id, graphObj } = this.state;
		const that = this;
		if (UserSession.isSystemKnowledge()) {
			let res = await knowledgeAtlasTree({ atlasId: id });
			console.log(res);
			this.setState({ data: res[0], }, () => {
				if (graphObj) {
					G6.Util.traverseTree(res[0], function(item) {
						item.nodeColor = that.fixColor(item.newType);
						item.textColor = that.fixTextColor(item.newType);
						item.childNumber = item.children ? item.children.length : 0;
						item.id = item.id ? item.id : item._id;
						item.name = item.name ? item.name : item.nodeName;
						item.nodeType = that.fixNodeType(item.newType);
					});
					graphObj.data(res[0]);
					graphObj.render();
					that.getCenter();
				}
			});
		} else {
			dispatch({
				type: "knowledgeGraphEdit/getGraphDetail",
				payload: {
					id: id,
					urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
				},
				callback: (res) => {
					console.log(res);
					this.setState({ data: res[0], }, () => {
						if (graphObj) {
							G6.Util.traverseTree(res[0], function(item) {
								item.nodeColor = that.fixColor(item.newType);
								item.textColor = that.fixTextColor(item.newType);
								item.childNumber = item.children ? item.children.length : 0;
								item.id = item.id ? item.id : item._id;
								item.name = item.name ? item.name : item.nodeName;
								item.nodeType = that.fixNodeType(item.newType);
							});
							graphObj.data(res[0]);
							graphObj.render();
							that.getCenter();
						}
					});
				},
			});
		}
	};

	addGraphNode = (nodeName, newType, parentId, callback) => {
		const { dispatch } = this.props;
		const { id } = this.state;
		const body = {
			graphNodeType: newType,
			title: nodeName,
			parentId,
			atlasId: id,
		};
		dispatch({
			type: "knowledgeGraphEdit/saveAndEditerNode",
			payload: body,
			callback: (res) => {
				callback(res);
			},
		});
	};

	removeCategoryNode = (id, callback) => {
		const { dispatch } = this.props;
		dispatch({
			type: "knowledgeGraphEdit/removeCategoryNode",
			payload: { id, },
			callback: (res) => {
				callback(res);
			},
		});
	};

	editCategoryNode = (_id, nodeName, callback) => {
		const { dispatch } = this.props;
		dispatch({
			type: "knowledgeGraphEdit/editerCategory",
			payload: { _id, nodeName, },
			callback: (res) => {
				callback(res);
			},
		});
	};

	showModal = (node, addNodeType, graphObj, nodeColor, textColor, val) => {
		let { type, selectNode } = this.state;
		if (addNodeType === 1) {
			type = "类别节点";
		} else {
			type = "意图节点";
		}
		this.setState({
			visible: true,
			type,
			selectNode: node,
			graphObj,
			addNodeType,
			nodeColor,
			textColor,
			defaultVal: val,
			nodeId: node.parentId,
		});
	};

	handleCancel = () => {
		this.setState({ visible: false });
	};

	handleCreate = () => {
		const { form } = this.formRef.props;
		const that = this;
		const { selectNode, graphObj, addNodeType, defaultVal } = this.state;
		form.validateFields((err, values) => {
			if (err) {
				return;
			}

			if (defaultVal) {
				that.editCategoryNode(
					selectNode.getModel().id,
					values.title,
					function() {
						graphObj.updateItem(selectNode, {
							name: values.title,
							nodeName: values.title,
						});
						form.resetFields();
						that.setState({
							visible: false,
							graphObj: null,
							selectNode: null,
							defaultVal: "",
						});
					}
				);
			} else {
				that.addGraphNode(values.title, addNodeType, selectNode.id, function(res) {
					console.log(res);
					const parentData = graphObj.findDataById(selectNode.id);
					if (!parentData.children) {
						parentData.children = [];
					}
					// 如果childData是一个数组，则直接赋值给parentData.children
					// 如果是一个对象，则使用parentData.children.push(obj)
					parentData.children.push({
						nodeName: values.title,
						id: res.data,
						graphNodeType: addNodeType,
						children: [],
						nodeColor: that.fixColor(addNodeType),
						textColor: that.fixTextColor(addNodeType),
						nodeType: that.fixNodeType(addNodeType),
						name: values.title,
						atlasId: that.state.id,
					});

					graphObj.changeData();
					// that.saveGraphNode(graphObj);
					form.resetFields();
					that.setState({
						visible: false,
						graphObj: null,
						selectNode: null,
						defaultVal: "",
					});
				});
			}

			// graphObj.refreshLayout(false);
		});
	};

	fixColor = (nodeType) => {
		if (nodeType === 0) {
			return "#318ff7";
		}
		if (nodeType === 1) {
			return "#f0b663";
		}
		return "#dce8f3";
	};

	fixTextColor = (nodeType) => {
		if (nodeType === 0 || nodeType === 1) {
			return "#fff";
		}
		return "#318ff7";
	};

	fixNodeType = (nodeType) => {
		if (nodeType === 0) {
			return "root";
		}
		if (nodeType === 1) {
			return "category";
		}
		if (nodeType === 2) {
			return "intention";
		}
		return "flow";
	};

	saveFormRef = (formRef) => {
		this.formRef = formRef;
	};

	editNode = (node, type, graph, bg, color, name) => {
		// 编辑节点
		console.log("编辑节点");
		let { selectNode, editShow, editMind } = this.state;
		if (selectNode.graphNodeType === 1 || selectNode.graphNodeType === 0) {
			editShow = true;
			this.TypeNodeInfo.openDrawer(node);
		}

		if (selectNode.graphNodeType === 2 || selectNode.graphNodeType === 3) {
			editMind = true;
			this.IntentionsNodeInfo.openDrawer(node);
		}

		this.setState({
			editShow,
			editMind,
			selectNodeNew: node,
		});
	};

	delNode = (id, graph) => {
		const that = this;

		confirm({
			title: "你确定要删除这个节点吗?",
			content: "",
			okText: "确定",
			okType: "danger",
			cancelText: "取消",
			onOk() {
				// graph.removeChild(id);
				that.removeCategoryNode(id, function(res) {
					graph.removeChild(id);
				});
				// that.saveGraphNode(graph);
			},
			onCancel() {},
		});
	};

	fixSelectNode = (selectNode, graph) => {
		this.setState({
			selectNode,
			graphObj: graph,
		});
	};

	saveGraphNode = (graph) => {
		graph.save();
	};

	getZoom = (num, graph) => {
		this.setState({
			graphScaleNum: num,
			graphObj: graph,
		});
	};

	getCenter = () => {
		const { graphObj } = this.state;
		if (graphObj) {
			// graphObj.fitView();
			graphObj.fitCenter();
			this.setState({
				graphScaleNum: 100,
			});
		}
	};

	/**
	 * 缩小
	 * @param graph
	 */
	doZoomIn = () => {
		const { graphObj } = this.state;
		if (graphObj) {
			const currentZoom = graphObj.getZoom();
			graphObj.zoomTo(currentZoom - 0.1);
			this.setState({
				graphScaleNum: parseInt(graphObj.getZoom() * 100),
			});
		}
	};

	/**
	 * 放大
	 */
	doZoomOut = () => {
		const { graphObj } = this.state;
		if (graphObj) {
			const currentZoom = graphObj.getZoom();
			graphObj.zoomTo(currentZoom + 0.1);
			this.setState({
				graphScaleNum: parseInt(graphObj.getZoom() * 100),
			});
		}
	};

	fixGraphObj = (graph) => {
		this.setState({
			graphObj: graph,
		});
	};

	onClose = (title, qaId, type) => {
		const { graphObj, selectNodeNew } = this.state;
		const item = graphObj.findById(selectNodeNew._cfg.id);
		const that = this;
		if (!type) {
			graphObj.updateItem(item, {
				qaId,
				name: title,
				nodeName: title,
			});
		} else {
			graphObj.updateItem(item, {
				qaId,
				name: title,
				nodeName: title,
				graphNodeType: type,
				nodeType: this.fixNodeType(type),
			});
		}

		that.setState({
			editShow: false,
			editMind: false,
			qaId,
		});
	};

	getQaIdBySearch = (arr, id) => {
		for (let i of arr) {
			if (i._id == id) {
				return i.qaId;
			}

			if (i.children && i.children.length > 0) {
				this.getQaIdBySearch(i.children, id);
			}
		}
	};

	/**
	 * 关闭编辑框后修改节点的名称
	 */
	resetNodeTitle = (title) => {
		const { graphObj, selectNodeNew } = this.state;
		const item = graphObj.findById(selectNodeNew._cfg.id);
		const that = this;
		if (title) {
			graphObj.updateItem(item, {
				name: title,
				nodeName: title,
			});
		}
	};

	/**
	 * 返回列表
	 */
	goBack = () => {
		window.location.href = "/knowledgeGraph";
	};

	render() {
		return (
			<GridContent>
				<Card style={{ background: "#fff", minHeight: "75vh" }}>
					{this.state.data ? (
						<KnowMap
							data={this.state.data}
							addCategory={this.showModal}
							editNode={this.editNode}
							delNode={this.delNode}
							fixSelectNode={this.fixSelectNode}
							zoom={this.getZoom}
							sendGraph={this.fixGraphObj}
						/>
					) : (
						<Spin tip='Loading...'>
							<div style={{ background: "#fff", height: "75vh" }} />
						</Spin>
					)}

					<AddCategoryModal
						wrappedComponentRef={this.saveFormRef}
						visible={this.state.visible}
						onCancel={this.handleCancel}
						onCreate={this.handleCreate}
						label={this.state.type}
						val={this.state.defaultVal}
					/>
					{/*{this.state.editShow ? (*/}
					{/*  // <TypeNodeEdit*/}
					{/*  //   visible={this.state.editShow}*/}
					{/*  //   node={this.state.selectNode}*/}
					{/*  //   close={this.onClose.bind(this)}*/}
					{/*  //   qaId={this.state.qaId}*/}
					{/*  // />*/}
					{/*) : (*/}
					{/*  ''*/}
					{/*)}*/}

					<Legend
						number={this.state.graphScaleNum}
						center={this.getCenter}
						zoomIn={this.doZoomIn}
						zoomOut={this.doZoomOut}
					/>
					<div
						style={{
							position: "absolute",
							top: 10,
							right: 10,
							cursor: "pointer",
						}}
						onClick={this.goBack}>
						<Icon type='rollback' style={{ marginRight: 10 }} />
						返回列表
					</div>
					{/*{this.state.editMind ? (*/}
					{/*  <Intentions*/}
					{/*    visible={this.state.editMind}*/}
					{/*    close={this.onClose.bind(this)}*/}
					{/*    node={this.state.selectNode}*/}
					{/*  />*/}
					{/*) : (*/}
					{/*  ''*/}
					{/*)}*/}
					<TypeNodeInfo
						onRef={(ref) => (this.TypeNodeInfo = ref)}
						resetNodeTitle={this.resetNodeTitle}
						atlasId={this.state.id}
					/>
					<IntentionsNodeInfo
						onRef={(ref) => (this.IntentionsNodeInfo = ref)}
						resetNodeTitle={this.resetNodeTitle}
						atlasId={this.state.id}
					/>
				</Card>
			</GridContent>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(GraphEdit);
